package com.blog.blog.controller;

import com.blog.blog.common.ApiBaseResponse;
import com.blog.blog.common.PageResponse;
import com.blog.blog.dto.SaveCategoryDTO;
import com.blog.blog.dto.SaveTagDTO;
import com.blog.blog.po.UserPO;
import com.blog.blog.service.CategoryService;
import com.blog.blog.service.TagService;
import com.blog.blog.service.oss.OssAdminService;
import com.blog.blog.vo.*;
import org.springframework.web.bind.annotation.*;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;

import java.util.List;
import java.util.Map;
import java.util.Set;

@Tag(name = "管理后台", description = "系统管理相关接口，包括内容管理、用户管理、权限管理等")
@SecurityRequirement(name = "Bearer")
@RestController
@RequestMapping("/api/admin")
public class AdminContentController {

    private final CategoryService categoryService;
    private final TagService tagService;
    private final OssAdminService ossAdminService;
    private final com.blog.blog.service.SystemService systemService;
    private final com.blog.blog.service.ArticleService articleService;
    private final com.blog.blog.service.SitemapService sitemapService;

    public AdminContentController(CategoryService categoryService,
                                  TagService tagService,
                                  OssAdminService ossAdminService,
                                  com.blog.blog.service.SystemService systemService,
                                  com.blog.blog.service.ArticleService articleService,
                                  com.blog.blog.service.SitemapService sitemapService) {
        this.categoryService = categoryService;
        this.tagService = tagService;
        this.ossAdminService = ossAdminService;
        this.systemService = systemService;
        this.articleService = articleService;
        this.sitemapService = sitemapService;
    }

    // 分类 CRUD
    @PostMapping("/categories")
    @com.blog.blog.util.annotations.RequirePerm({"category:manage"})
    public ApiBaseResponse<Boolean> createCategory(@RequestBody SaveCategoryDTO dto) {
        return ApiBaseResponse.success(categoryService.create(dto));
    }

    @PutMapping("/categories/{id}")
    @com.blog.blog.util.annotations.RequirePerm({"category:manage"})
    public ApiBaseResponse<Boolean> updateCategory(@PathVariable Long id, @RequestBody SaveCategoryDTO dto) {
        return ApiBaseResponse.success(categoryService.update(id, dto));
    }

    @DeleteMapping("/categories/{id}")
    @com.blog.blog.util.annotations.RequirePerm({"category:manage"})
    public ApiBaseResponse<Boolean> deleteCategory(@PathVariable Long id) {
        return ApiBaseResponse.success(categoryService.delete(id));
    }

    // 标签 CRUD
    @PostMapping("/tags")
    @com.blog.blog.util.annotations.RequirePerm({"tag:manage"})
    public ApiBaseResponse<Boolean> createTag(@RequestBody SaveTagDTO dto) {
        return ApiBaseResponse.success(tagService.create(dto));
    }

    @PutMapping("/tags/{id}")
    @com.blog.blog.util.annotations.RequirePerm({"tag:manage"})
    public ApiBaseResponse<Boolean> updateTag(@PathVariable Long id, @RequestBody SaveTagDTO dto) {
        return ApiBaseResponse.success(tagService.update(id, dto));
    }

    @DeleteMapping("/tags/{id}")
    @com.blog.blog.util.annotations.RequirePerm({"tag:manage"})
    public ApiBaseResponse<Boolean> deleteTag(@PathVariable Long id) {
        return ApiBaseResponse.success(tagService.delete(id));
    }

    // OSS 文件管理：查看（分页 + 关键字）
    @GetMapping("/oss")
    @com.blog.blog.util.annotations.RequirePerm({"oss:manage"})
    public ApiBaseResponse<PageResponse<OssFileVO>> listOss(
            @RequestParam(required = false) Integer status,
            @RequestParam(required = false) String q,
            @RequestParam(required = false) Integer pageNo,
            @RequestParam(required = false) Integer pageSize) {
        return ApiBaseResponse.success(ossAdminService.pageList(status, q, pageNo, pageSize));
    }

    // OSS 文件管理：删除（先删 OSS，再删库）
    @DeleteMapping("/oss")
    @com.blog.blog.util.annotations.RequirePerm({"oss:manage"})
    public ApiBaseResponse<Boolean> deleteOss(@RequestParam("key") String key) {
        ossAdminService.deleteByKey(key);
        return ApiBaseResponse.success(true);
    }

    // OSS 文件管理：批量清理未使用文件（仅删除 status=0 的对象）
    @DeleteMapping("/oss/cleanup")
    @com.blog.blog.util.annotations.RequirePerm({"oss:manage"})
    public ApiBaseResponse<Integer> cleanupUnused(@RequestParam(required = false, defaultValue = "true") boolean verify) {
        return ApiBaseResponse.success(ossAdminService.cleanupUnused(verify));
    }

    // OSS 文件管理：状态设置（使用中/未使用）
    @PutMapping("/oss/status")
    @com.blog.blog.util.annotations.RequirePerm({"oss:manage"})
    public ApiBaseResponse<Boolean> setStatus(@RequestParam("url") String url, @RequestParam("status") Integer status) {
        ossAdminService.setStatus(url, status);
        return ApiBaseResponse.success(true);
    }

    // OSS 文件管理：校验对象是否存在（直连 OSS）
    @GetMapping("/oss/exists")
    @com.blog.blog.util.annotations.RequirePerm({"oss:manage"})
    public ApiBaseResponse<Boolean> exists(@RequestParam("key") String key) {
        return ApiBaseResponse.success(ossAdminService.exists(key));
    }

    // OSS 文件管理：查询引用（文章/简历）
    @GetMapping("/oss/references")
    @com.blog.blog.util.annotations.RequirePerm({"oss:manage"})
    public ApiBaseResponse<Set<String>> references(@RequestParam("type") String type,
                                                   @RequestParam("id") Long id) {
        return ApiBaseResponse.success(ossAdminService.references(type, id));
    }

    // 角色/权限 列表（只读）
    @GetMapping("/roles")
    @com.blog.blog.util.annotations.RequirePerm({"role:manage"})
    public ApiBaseResponse<List<RoleVO>> listRoles(@RequestParam(required = false) String keyword) {
        return ApiBaseResponse.success(systemService.listRoles(keyword));
    }

    @GetMapping("/permissions")
    @com.blog.blog.util.annotations.RequirePerm({"permission:manage"})
    public ApiBaseResponse<List<PermissionVO>> listPermissions(@RequestParam(required = false) String keyword) {
        return ApiBaseResponse.success(systemService.listPermissions(keyword));
    }

    // 角色 CRUD（最小）
    @PostMapping("/roles")
    @com.blog.blog.util.annotations.RequirePerm({"role:manage"})
    public ApiBaseResponse<Map<String,Object>> createRole(@RequestBody com.blog.blog.dto.SaveRoleDTO dto) {
        systemService.createRole(dto);
        java.util.Map<String,Object> m = new java.util.HashMap<>();
        return ApiBaseResponse.success(m);
    }

    @PutMapping("/roles/{id}")
    @com.blog.blog.util.annotations.RequirePerm({"role:manage"})
    public ApiBaseResponse<Boolean> updateRole(@PathVariable Long id, @RequestBody com.blog.blog.dto.SaveRoleDTO dto) {
        return ApiBaseResponse.success(systemService.updateRole(id, dto));
    }

    @DeleteMapping("/roles/{id}")
    @com.blog.blog.util.annotations.RequirePerm({"role:manage"})
    public ApiBaseResponse<Boolean> deleteRole(@PathVariable Long id) {
        return ApiBaseResponse.success(systemService.deleteRole(id));
    }

    // 权限 CRUD（最小）
    @PostMapping("/permissions")
    @com.blog.blog.util.annotations.RequirePerm({"permission:manage"})
    public ApiBaseResponse<Map<String,Object>> createPermission(@RequestBody com.blog.blog.dto.SavePermissionDTO dto) {
        try {
            Long id = systemService.createPermission(dto);
            java.util.Map<String,Object> result = new java.util.HashMap<>();
            result.put("id", id);
            return ApiBaseResponse.success(result);
        } catch (org.springframework.dao.DuplicateKeyException e) {
            return ApiBaseResponse.error(400, "权限编码已存在，请使用不同的编码");
        } catch (Exception e) {
            return ApiBaseResponse.error(500, "创建权限失败：" + e.getMessage());
        }
    }

    @PutMapping("/permissions/{id}")
    @com.blog.blog.util.annotations.RequirePerm({"permission:manage"})
    public ApiBaseResponse<Boolean> updatePermission(@PathVariable Long id, @RequestBody com.blog.blog.dto.SavePermissionDTO dto) {
        return ApiBaseResponse.success(systemService.updatePermission(id, dto));
    }

    @DeleteMapping("/permissions/{id}")
    @com.blog.blog.util.annotations.RequirePerm({"permission:manage"})
    public ApiBaseResponse<Boolean> deletePermission(@PathVariable Long id) {
        return ApiBaseResponse.success(systemService.deletePermission(id));
    }

    // 角色权限分配
    @PostMapping("/roles/{id}/perms")
    @com.blog.blog.util.annotations.RequirePerm({"role:manage"})
    public ApiBaseResponse<Boolean> setRolePerms(@PathVariable("id") Long roleId, @RequestBody java.util.List<Long> permIds) {
        return ApiBaseResponse.success(systemService.setRolePerms(roleId, permIds));
    }

    @GetMapping("/roles/{id}/perms")
    @com.blog.blog.util.annotations.RequirePerm({"role:manage"})
    public ApiBaseResponse<List<Long>> getRolePerms(@PathVariable("id") Long roleId) {
        return ApiBaseResponse.success(systemService.getRolePermIds(roleId));
    }

    // 用户-角色绑定
    @GetMapping("/users/{id}/roles")
    @com.blog.blog.util.annotations.RequirePerm({"user:manage"})
    public ApiBaseResponse<List<Long>> getUserRoles(@PathVariable("id") Long userId) {
        return ApiBaseResponse.success(systemService.getUserRoleIds(userId));
    }

    @PostMapping("/users/{id}/roles")
    @com.blog.blog.util.annotations.RequirePerm({"user:manage"})
    public ApiBaseResponse<Boolean> setUserRoles(@PathVariable("id") Long userId, @RequestBody java.util.List<Long> roleIds) {
        return ApiBaseResponse.success(systemService.setUserRoles(userId, roleIds));
    }

    // 用户分页搜索
    @GetMapping("/users")
    @com.blog.blog.util.annotations.RequirePerm({"user:manage"})
    public ApiBaseResponse<PageResponse<UserPO>> pageUsers(@RequestParam(required = false) String q,
                                                           @RequestParam Integer pageNo,
                                                           @RequestParam Integer pageSize) {
        return ApiBaseResponse.success(systemService.pageUsers(q, pageNo, pageSize));
    }

    // 操作日志分页
    @GetMapping("/oplogs")
    @com.blog.blog.util.annotations.RequirePerm({"permission:manage"})
    public ApiBaseResponse<PageResponse<OperationLogVO>> pageOpLogs(@RequestParam(required = false) String q,
                                                                    @RequestParam(required = false) Integer status,
                                                                    @RequestParam Integer pageNo,
                                                                    @RequestParam Integer pageSize) {
        return ApiBaseResponse.success(systemService.pageOperationLogs(q, status, pageNo, pageSize));
    }

    // 系统配置
    @GetMapping("/configs")
    @com.blog.blog.util.annotations.RequirePerm({"permission:manage"})
    public ApiBaseResponse<List<SystemConfigVO>> listConfigs(@RequestParam(required = false) String prefix) {
        return ApiBaseResponse.success(systemService.listConfigs(prefix));
    }

    @PostMapping("/configs")
    @com.blog.blog.util.annotations.RequirePerm({"permission:manage"})
    public ApiBaseResponse<Boolean> upsertConfig(@RequestBody java.util.Map<String, String> body) {
        String key = body.get("key");
        String value = body.get("value");
        String description = body.get("description");
        return ApiBaseResponse.success(systemService.upsertConfig(key, value, description));
    }

    // 缓存管理（Redis）
    @GetMapping("/cache/keys")
    @com.blog.blog.util.annotations.RequirePerm({"permission:manage"})
    public ApiBaseResponse<List<String>> scanCacheKeys(@RequestParam(required = false) String pattern,
                                                       @RequestParam(required = false) Integer limit) {
        return ApiBaseResponse.success(systemService.scanRedisKeys(pattern, limit));
    }

    @DeleteMapping("/cache")
    @com.blog.blog.util.annotations.RequirePerm({"permission:manage"})
    public ApiBaseResponse<Long> deleteCache(@RequestParam(required = false) String pattern) {
        return ApiBaseResponse.success(systemService.deleteRedisKeysByPattern(pattern));
    }

    @GetMapping("/cache/ping")
    @com.blog.blog.util.annotations.RequirePerm({"permission:manage"})
    public ApiBaseResponse<Boolean> cachePing() {
        return ApiBaseResponse.success(systemService.redisPing());
    }

    // 在线会话管理
    @GetMapping("/sessions")
    @com.blog.blog.util.annotations.RequirePerm({"user:manage"})
    public ApiBaseResponse<List<OnlineSessionVO>> listSessions(@RequestParam(required = false) String q) {
        return ApiBaseResponse.success(systemService.listOnlineSessions(q));
    }

    @DeleteMapping("/sessions/{token}")
    @com.blog.blog.util.annotations.RequirePerm({"user:manage"})
    public ApiBaseResponse<Boolean> kickout(@PathVariable("token") String token) {
        return ApiBaseResponse.success(systemService.kickoutToken(token));
    }

    // 管理端：文章分页（带数据权限：SELF 仅看本人）
    @GetMapping("/articles")
    @com.blog.blog.util.annotations.RequirePerm({"article:read"})
    public ApiBaseResponse<PageResponse<ArticleListItemVO>> adminPageArticles(
            @RequestParam Integer pageNo,
            @RequestParam Integer pageSize,
            @RequestParam(required = false) String keyword,
            @RequestParam(required = false) Integer status
    ) {
        com.blog.blog.dto.ArticleListQueryDTO q = new com.blog.blog.dto.ArticleListQueryDTO();
        q.setPageNo(pageNo);
        q.setPageSize(pageSize);
        q.setKeyword(keyword);
        q.setStatus(status);
        Long userId = currentUserId();
        if (systemService.isSelfDataScope(userId)) {
            q.setAuthorId(userId);
        }
        return ApiBaseResponse.success(articleService.pageArticles(q));
    }

    private Long currentUserId() {
        try {
            jakarta.servlet.http.HttpServletRequest req = ((org.springframework.web.context.request.ServletRequestAttributes) org.springframework.web.context.request.RequestContextHolder.currentRequestAttributes()).getRequest();
            Object v = req.getAttribute("X-User-Id");
            if (v instanceof Long) return (Long) v;
            if (v instanceof String) return Long.parseLong((String) v);
        } catch (Exception ignore) {}
        return null;
    }

    // SEO 与站点地图管理
    @Operation(summary = "生成站点地图", description = "手动触发站点地图生成")
    @PostMapping("/sitemap/generate")
    @com.blog.blog.util.annotations.RequirePerm({"permission:manage"})
    public ApiBaseResponse<Boolean> generateSitemap() {
        try {
            sitemapService.generateSitemap();
            return ApiBaseResponse.success(true);
        } catch (Exception e) {
            return ApiBaseResponse.error(500, "生成站点地图失败: " + e.getMessage());
        }
    }

    @Operation(summary = "清除站点地图缓存", description = "清除站点地图相关缓存")
    @DeleteMapping("/sitemap/cache")
    @com.blog.blog.util.annotations.RequirePerm({"permission:manage"})
    public ApiBaseResponse<Boolean> clearSitemapCache() {
        try {
            sitemapService.clearSitemapCache();
            return ApiBaseResponse.success(true);
        } catch (Exception e) {
            return ApiBaseResponse.error(500, "清除缓存失败: " + e.getMessage());
        }
    }

    @Operation(summary = "提交站点地图到搜索引擎", description = "提交站点地图到Google、Bing等搜索引擎")
    @PostMapping("/sitemap/submit")
    @com.blog.blog.util.annotations.RequirePerm({"permission:manage"})
    public ApiBaseResponse<Boolean> submitSitemap() {
        try {
            sitemapService.submitSitemapToSearchEngines();
            return ApiBaseResponse.success(true);
        } catch (Exception e) {
            return ApiBaseResponse.error(500, "提交站点地图失败: " + e.getMessage());
        }
    }

    // 数据权限判断改由 systemService 提供
}


